(function() {

    window.onload = function() {
        game.init();
    }

    var game = window.game = {
        width: 0,
        height: 0,
        asset: null,
        stage: null,
        ticker: null,
        state: null,
        score: 0,
		groupValue:1,
		containerScore:null,
        bg: null,
        ground: null,
        bird: null,
		yun0: null,
		yun1: null,
		yun2: null,
		yun3: null,
		elem: null,
		hu: null,
		txicon:null,
		zhongzi:null,
		miao:null,
		ycall:null,
		biggua:null,
		smallgua:null,
		jsicon:null,
        holdbacks: null,
        gameReadyScene: null,
        gameOverScene: null,
		growthScene: null,
		GroundScene: null,
		OpenWinScene:null,
		OpenWinSceneDiv:null,
		OpenWinSceneMyGua:null,
		InitData:null,
		watering:null,
		activeContent:null,
		authKey:getUrlParam("authKey"),
        init: function() {
            this.asset = new game.Asset();
            this.asset.on('complete', function(e) {
                this.asset.off('complete');
				//初始化数据
				this.initData();
                this.initStage();
            }.bind(this));
            this.asset.load();
        },
		initData: function(){
			let that = this
			postAjax2({
			    id: 2,
			    method: "watermelon_homeindexinfo",
			    params: {
			        "authKey": this.authKey,
			        "activityId": 41
			    }
			}, function (datas) {
			    console.log(JSON.stringify(datas))
				if(!utilsClass.isEmpty(datas)){
					that.InitData = datas
				}
			});
		},
        initStage: function() {
            // this.width = Math.min(innerWidth, 450) * 2;
            // this.height = Math.min(innerHeight, 750) * 2;
			this.width = window.innerWidth*2 || document.documentElement.clientWidth*2;
			this.height = window.innerHeight*2 || document.documentElement.clientHeight*2;
            this.scale = 0.5;

            //舞台画布
            var renderType = location.search.indexOf('dom') != -1 ? 'dom' : 'canvas';

            //舞台
            this.stage = new Hilo.Stage({
                renderType: renderType,
                width: this.width,
                height: this.height,
                scaleX: this.scale,
                scaleY: this.scale
            });
            document.body.appendChild(this.stage.canvas);

            //启动计时器
            this.ticker = new Hilo.Ticker(60);
            this.ticker.addTick(Hilo.Tween);
            this.ticker.addTick(this.stage);
            this.ticker.start(true);

            //绑定交互事件
            this.stage.enableDOMEvent(Hilo.event.POINTER_START, true);
            this.stage.on(Hilo.event.POINTER_START, this.onUserInput.bind(this));

            //Space键控制
            // if (document.addEventListener) {
            //     document.addEventListener('keydown', function(e) {
            //         if (e.keyCode === 32) this.onUserInput(e);
            //     }.bind(this));
            // } else {
            //     document.attachEvent('onkeydown', function(e) {
            //         if (e.keyCode === 32) this.onUserInput(e);
            //     }.bind(this));
            // }

            //舞台更新
            this.stage.onUpdate = this.onUpdate.bind(this);

            //初始化
            this.initBackground();
			
			
			
            this.initScenes();
			this.initHu();
			this.initYun();
			this.initGrowth();
			this.initZhongZ();
			this.initYcall();
			this.initCurrentScore();
            // this.initHoldbacks();
            // this.initBird();
            //准备游戏
            this.gameReady();
        },

        initBackground: function() {
            //背景
            var bgWidth = this.width * this.scale;
            var bgHeight = this.height * this.scale;

            var bgImg = this.asset.bg;
            this.bg = new Hilo.Bitmap({
                id: 'bg',
                image: bgImg,
                scaleX: this.width / bgImg.width,
                scaleY: this.height / bgImg.height
            }).addTo(this.stage);
			
			
			var myxigua = new Hilo.Bitmap({
			    id: 'myxigua',
			    image: this.asset.myxigua,
				x:20,
				y:this.height * .9,
			    scaleX: .78,
			    scaleY: .78
			}).addTo(this.stage);

			var gamerule = new Hilo.Bitmap({
			    id: 'gamerule',
				x:155,
				y:this.height * .9,
			    image: this.asset.gamerule,
			    scaleX: .78,
			    scaleY: .78
			}).addTo(this.stage);
			
			myxigua.on(Hilo.event.POINTER_START, function(e) {
			    e.stopImmediatePropagation && e.stopImmediatePropagation();
			    this.OpenWinSceneMyGua.show()
			}.bind(this));
			
			gamerule.on(Hilo.event.POINTER_START, function(e) {
			    e.stopImmediatePropagation && e.stopImmediatePropagation();
			    this.OpenWinSceneDiv.show()
			}.bind(this));
			
			
			
			

            //地面
            // var groundImg = this.asset.ground;
            // var groundOffset = 60;
            // this.ground = new Hilo.Bitmap({
            //     id: 'ground',
            //     image: groundImg,
            //     scaleX: (this.width + groundOffset * 2) / groundImg.width
            // }).addTo(this.stage);

            // //设置地面的y轴坐标
            // this.ground.y = this.height - this.ground.height;

            // //移动地面
            // Hilo.Tween.to(this.ground, {
            //     x: -groundOffset * this.ground.scaleX
            // }, {
            //     duration: 400,
            //     loop: true
            // });
        },

        initCurrentScore: function() {
			let that = this;
            //当前分数
   //          this.currentScore = new Hilo.BitmapText({
   //              id: 'score',
   //              glyphs: this.asset.numberGlyphs,
   //              textAlign: 'center'
   //          }).addTo(this.stage);

   //          //设置当前分数的位置
   //          //this.currentScore.x = this.width - this.currentScore.width >> 1;
			// this.currentScore.x = this.width - 70 >> 0;
   //          this.currentScore.y = this.height*0.885;
			
			this.containerScore = new Hilo.Container({
				id:"containerScore",
			    //x:winWidth * .5,
				x:this.width,
			    y:this.height * .93,
			    // background:"#000",
			    width: this.width/3,
			    height: 100,
				pivotX:this.width/3,
				pivotY:100,
				alpha:.9,
				textAlign: 'right'
			}).addTo(this.stage);
			
			//容器
			var container = that.containerScore
			var bmp = new Hilo.BitmapText({
				id:"numBmp",
				glyphs:Hilo.BitmapText.createGlyphs("0123456789X", this.asset.newnum),
				x:container.width*.48,
				y:container.height *.36,
				width: 12,
				pivotX:.5,
				pivotY:.5,
				scaleX:1,
				scaleY:1,
				//clipChildren:true,
				textAlign:"left",
				letterSpacing:2
			}).setText("X" + this.score);
			// bmp.pivotX = bmp.width * .5;
			// bmp.pivotY = bmp.height * .5;
			
			var righttar = new Hilo.Bitmap({
				id:"righttar",
				image: this.asset.righttar,
				x:0,
				y:0,
				rect: [0, 0, 260, 108],
				width: container.width,
				height: container.height,
				depth:9,
				scaleX:1,
				scaleY:1
			})
			
			var bighu = new Hilo.Bitmap({
				id:"bighu",
				image: this.asset.bighu,
				x:10,
				y:.5,
				rect: [0, 0, 83, 84],
				depth:9,
				scaleX:1,
				scaleY:1
			})
			bighu.y = righttar.height *.07
			//console.log(bmp.pivotX+"-"+bmp.pivotY)
			container.addChild(righttar,bmp, bighu);
			
			//点击
			// this.containerScore.on(Hilo.event.POINTER_START, function(e) {
			//     e.stopImmediatePropagation && e.stopImmediatePropagation();
			// 	console.log(this.score)
			// }.bind(this));
			
			
			
			// let font = "40px arial";
			// this.elem = new Hilo.DOMElement({
			//     element: Hilo.createElement('div', {
			//         innerHTML: this.content,
			//         style: {
			//             position: 'absolute',
			//             font: font,
			// 			color:'RED',
			// 			fontWeight: 'bold'
			//         }
			//     }),
			//     width: 'auto',
			//     height: 'auto',
			//     x: this.width*.82 >> 0,
			//     y: this.height * 0.882
			// }).addTo(container);
        },
		initZhongZ:function(){
			// var zhongzi = new Hilo.Sprite({
			//     frames: this.asset.zhongziAtlas.getSprite('zhongzi'),
			//     x: 0,
			//     y: 100,
			//     interval: 6,
			//     timeBased: false,
			//     loop: true,
			//     onUpdate: function(){
			//         // if(this.x > stage.width - this.pivotX){
			//         //     this.x = 0;
			//         // }else{
			//         //     this.x += 3;
			//         // }
			//     }
			// }).addTo(this.stage);
			this.zhongzi = new game.Zhongzi({
			    id: 'zhongzi',
			    atlas: this.asset.zhongziAtlas,
			}).addTo(this.GroundScene);
			
			this.miao = new game.Miao({
			    id: 'miao',
			    atlas: this.asset.miaoiconAtlas,
			}).addTo(this.GroundScene);
			this.biggua = new game.BigGua({
			    id: 'biggua',
			    atlas: this.asset.bigguaAtlas,
			}).addTo(this.GroundScene);
			this.small = new game.SmallGua({
			    id: 'smallgua',
			    atlas: this.asset.smallguaAtlas,
			}).addTo(this.GroundScene);
			
			this.jsicon = new game.JsIcon({
			    id: 'jsicon',
			    atlas: this.asset.jsiconAtlas,
			}).addTo(this.GroundScene);
			
			// this.smallgua = new game.SmallBua({
			//     id: 'smallgua',
			//     atlas: this.asset.smallguaAtlas,
			// }).addTo(this.GroundScene);
			
			
			// this.miao = new game.Miao({
			//     id: 'miao',
			//     atlas: this.asset.miaoiconAtlas,
			// }).addTo(this.GroundScene);
			
			// this.zhongzi = new game.Zhongzi({
			//     id: 'zhongzi',
			//     atlas: this.asset.zhongziAtlas,
			//     startX: this.width* .5,
			//     startY: this.height* .68,
			//     endX: this.width* .5,
			//     endY: this.height* .68,
			//     startRot:0,
			//     endRot:0,
			//     scale:1,
			// 	// easeDo:Hilo.Ease.Expo.EaseInOut,
			// 	duration:500
			// }).addTo(this.stage);
		},
		//成长值
		initGrowth: function(){
			//console.log(this.GroundScene.getChildById)
			this.growthScene = new game.Growth({
			    id: 'growth',
				x:this.width*.5,
				y:this.GroundScene.y+this.GroundScene.getChildById('waiground').height+50,
				width:this.width,
				height:80,
			    image: [this.asset.kuan,this.asset.tiao,this.asset.tiaoback],
				// background:"red",
			    visible: true
			}).addTo(this.stage);
			//console.log(this.growthScene.width +"-" + this.growthScene.height)
			this.growthScene.pivotX = this.growthScene.width *.5;
			this.growthScene.pivotY = this.growthScene.height *.5;
		},
		initYun: function(){
			this.yun0 = new game.Yun({
			    id: 'yun0',
			    atlas: this.asset.yunAtlas1,
			    startX: 80,
			    startY: this.height* .05,
				endX:160,
				endY:this.height * .05+10,
				startRot:0,
				endRot:-5,
				scale:1,
				easeDo:Hilo.Ease.Quad.EaseIn,
				duration:15000
			}).addTo(this.stage);
			this.yun1 = new game.Yun({
			    id: 'yun1',
			    atlas: this.asset.yunAtlas2,
			    startX: this.width*.7,
			    startY: this.height* .1,
				endX: this.width-100,
				endY: this.height* .1+10,
				startRot:0,
				endRot:0,
				scale:1,
				easeDo:Hilo.Ease.Back.EaseInOut,
				duration:80000
			}).addTo(this.stage);
			
		},
		initHu: function(){
			this.hu = new game.Hu({
			    id: 'hu',
			    atlas: this.asset.huAtlas,
				scale:1,
				//easeDo:Hilo.Ease.Expo.EaseInOut,
				duration:500
			}).addTo(this.GroundScene)
			
			this.txicon = new game.TxIcon({
			    id: 'txicon',
			    atlas: this.asset.txiconAtlas,
				scale:1,
				//easeDo:Hilo.Ease.Expo.EaseInOut,
				duration:500
			}).addTo(this.GroundScene)
			//.addTo(this.stage);
			//事件
			let btnState = false
			this.hu.on(Hilo.event.POINTER_START, function(e) {
			    e.stopImmediatePropagation && e.stopImmediatePropagation()
				let that = this
				let num = 0
				
				if(that.score>0 && !utilsClass.isEmpty(that.watering)){
					if(that.InitData.watermelon.iswatering){
						
						if(!btnState){
							btnState = true
							postAjax2({
							    id: 2,
							    method: "watermelon_watering",
							    params: {
							        "authKey": window.game.authKey,
							        "activityId": 41,
									"farmId":that.InitData.watermelon.farmId
							    }
							}, function (datas) {
							    console.log(JSON.stringify(datas))
								that.InitData = datas
								that.hu.visible = false
								that.jsicon.getReady(that.hu,that.InitData.myCurveValue)
								
								var intid = self.setInterval(function(){
									that.score--
									//水滴数
									that.containerScore.getChildById("numBmp").setText("X"+ that.score)
									//成长值
									that.growthScene.doClick(that.groupValue++);
									//播放浇水动画1次 用按钮状态判断
									//西瓜长大动画1次 用按钮状态判断
									num++
									if(num>that.watering-1){
										self.clearInterval(intid);
										btnState = false
										
										//结束了
										if(that.groupValue>199){
											
											//判断收割
											setTimeout(()=>{
												that.GroundScene.getChildById('hu').removeFromParent()
												that.OpenWinScene.show()
											},1000)
										//if(that.myCurveValue<1){
											// setTimeout(()=>{
											// 	//特效果
											// 	that.txicon.goto(0,false)
											// },500)
											// console.log(that.score)
											// console.log(that.groupValue)
											
											//}
											//that.hu.visible = false
										}else{
											console.log(that.InitData.watermelon)
											switch(that.InitData.watermelon.curveValue) {
											     case 50:
											        console.log("苗")
													that.GroundScene.huTween.stop()
													that.GroundScene.getChildById('hu').y = -100
													that.GroundScene.huTween = Hilo.Tween.to(that.GroundScene.getChildById('hu'), {x:that.GroundScene.getChildById('hu').x ,y:that.GroundScene.getChildById('hu').y-10, rotation:0}, {duration:500,ease:null, reverse:true, loop:true});
													setTimeout(()=>{
														
														that.GroundScene.getChildById('zhongzi').visible = false
														that.GroundScene.getChildById('zhongzi').stop()
														that.GroundScene.getChildById('miao').visible = true
														that.GroundScene.getChildById('miao').getReady()
														//特效果
														that.GroundScene.getChildById('txicon').visible = true
														that.GroundScene.getChildById('txicon').goto(0,false)
													},500)
													
											        break;
											     case 100:
													that.GroundScene.huTween.stop()
													that.GroundScene.getChildById('hu').y = -115
													that.GroundScene.huTween = Hilo.Tween.to(that.GroundScene.getChildById('hu'), {x:that.GroundScene.getChildById('hu').x ,y:that.GroundScene.getChildById('hu').y-10, rotation:0}, {duration:500,ease:null, reverse:true, loop:true});
													setTimeout(()=>{
														
														that.GroundScene.getChildById('miao').visible = false
														that.GroundScene.getChildById('miao').stop()
														that.GroundScene.getChildById('smallgua').visible = true
														that.GroundScene.getChildById('smallgua').getReady()
														//特效果
														that.GroundScene.getChildById('txicon').visible = true
														that.GroundScene.getChildById('txicon').goto(0,false)
													},500)
											        break;
												case 150:
													//console.log(that.GroundScene.huTween)
													that.GroundScene.huTween.stop()
													that.GroundScene.getChildById('hu').y = -130
													that.GroundScene.huTween = Hilo.Tween.to(that.GroundScene.getChildById('hu'), {x:that.GroundScene.getChildById('hu').x ,y:that.GroundScene.getChildById('hu').y-10, rotation:0}, {duration:500,ease:null, reverse:true, loop:true});
													setTimeout(()=>{
														
														that.GroundScene.getChildById('smallgua').visible = false
														that.GroundScene.getChildById('smallgua').stop()
														that.GroundScene.getChildById('biggua').visible = true
														that.GroundScene.getChildById('biggua').getReady()
														//特效果
														that.GroundScene.getChildById('txicon').visible = true
														that.GroundScene.getChildById('txicon').goto(0,false)
													},500)
												   break;
												case 0:
													that.GroundScene.huTween.stop()
													that.GroundScene.getChildById('hu').y = -60
													that.GroundScene.huTween = Hilo.Tween.to(that.GroundScene.getChildById('hu'), {x:that.GroundScene.getChildById('hu').x ,y:that.GroundScene.getChildById('hu').y-10, rotation:0}, {duration:500,ease:null, reverse:true, loop:true});
													setTimeout(()=>{
														//特效果
														that.GroundScene.getChildById('txicon').visible = true
														that.GroundScene.getChildById('txicon').goto(0,false)
													},500)
													break;
											    default:
											       console.log("开始")
											}
											console.log(that.score)
										}
									}
								},30);
									
							});
							
							
						}
					}else{
						$.alert("您浇水壶中的水滴不够，无法进行此次操作","提示",function(){})
					}
					
				}else if(utilsClass.isEmpty(that.watering)){
					$.alert("游戏初始化异常，请稍后在试！","提示",function(){})
				}else{
					$.alert("您的浇水壶中已经没有蓄水了，请先获取水滴","提示",function(){})
				}
				//this.hu.visible = false
				// this.elem.drawable.domElement.innerHTML="X"+count++;
			}.bind(this));
		},

        initBird: function() {
            this.bird = new game.Bird({
                id: 'bird',
                atlas: this.asset.birdAtlas,
                startX: 100,
                startY: this.height >> 1,
                groundY: this.ground.y - 12
            }).addTo(this.stage, this.ground.depth - 1);
        },
		
		initWatering: function() {
		    this.bird = new game.Watering({
		        id: 'water',
		        atlas: this.asset.waterAtlas,
		        startX: 100,
		        startY: this.height >> 1,
		        groundY: this.ground.y - 12
		    }).addTo(this.stage, this.bg.depth - 2);
		},
		
		initYcall: function() {
		    this.ycall = new game.Ycall({
		        id: 'ycall',
		        atlas: this.asset.ycallAtlas,
		        startX: this.width * .027,
		        startY: this.height * .15,
				scale:1,
		    }).addTo(this.stage);
		},

        initHoldbacks: function() {
            this.holdbacks = new game.Holdbacks({
                id: 'holdbacks',
                image: this.asset.holdback,
                height: this.height,
                startX: this.width + 200,
                groundY: this.ground.y
            }).addTo(this.stage, this.ground.depth - 1);
        },

        initScenes: function() {
			this.GroundScene = new game.GroundScene({
			    id: 'groundScene',
			    width: this.width,
				y:this.height *.67,
				background:"#000000",
				hu:this.hu,
			    image: [this.asset.waiground,this.asset.neiground,this.asset.neijia,this.asset.niba,this.asset.shou]
			}).addTo(this.stage);
			
			this.OpenWinScene = new game.OpenWinScene({
			    id: 'openWinScene',
			    width: this.width,
			    height: this.height,
			    image: [this.asset.box,this.asset.btn1,this.asset.cha]
			}).addTo(this.stage);
			
			this.OpenWinSceneDiv = new game.OpenWinSceneDiv({
			    id: 'openWinSceneDiv',
			    width: this.width,
			    height: this.height,
			    image: [this.asset.bigbox,this.asset.btn2,this.asset.cha]
			}).addTo(this.stage);
			this.OpenWinSceneMyGua = new game.OpenWinSceneMyGua({
			    id: 'openWinSceneMyGua',
			    width: this.width,
			    height: this.height,
			    image: [this.asset.bigbox,this.asset.btn2,this.asset.cha]
			}).addTo(this.stage);
			
			
            //准备场景
            // this.gameReadyScene = new game.ReadyScene({
            //     id: 'readyScene',
            //     width: this.width,
            //     height: this.height,
            //     image: this.asset.ready
            // }).addTo(this.stage);

            // //结束场景
            // this.gameOverScene = new game.OverScene({
            //     id: 'overScene',
            //     width: this.width,
            //     height: this.height,
            //     image: this.asset.over,
            //     numberGlyphs: this.asset.numberGlyphs,
            //     visible: false
            // }).addTo(this.stage);

            //绑定开始按钮事件
            // this.gameOverScene.getChildById('start').on(Hilo.event.POINTER_START, function(e) {
            //     e.stopImmediatePropagation && e.stopImmediatePropagation();
            //     this.gameReady();
            // }.bind(this));
			
        },

        onUserInput: function(e) {
            // if (this.state !== 'over' && !this.gameOverScene.contains(e.eventTarget)) {
            //     //启动游戏场景
            //     if (this.state !== 'playing') this.gameStart();
            //     //控制小鸟往上飞
            //     this.bird.startFly();
            // }
        },

        onUpdate: function(delta) {
            if (this.state === 'ready') {
                return;
            }

            if (this.bird.isDead) {
                this.gameOver();
            } else {
                this.currentScore.setText(this.calcScore());
                //碰撞检测
                if (this.holdbacks.checkCollision(this.bird)) {
                    this.gameOver();
                }
            }
        },

        gameReady: function() {
            //this.gameOverScene.hide();
            this.state = 'ready';
            this.score = this.InitData.myGrowthValue;
			this.watering = this.InitData.watering;
			this.groupValue = this.InitData.myCurveValue;
			this.activeContent = this.InitData.activeContent;
			this.yun0.getReady();
			this.yun1.getReady();
			//this.yun2.getReady();
			// this.hu.getReady();
			this.zhongzi.getReady();
			this.ycall.getReady();
			this.growthScene.getReady();
			//this.OpenWinScene.show();
			this.GroundScene.doShow(this.InitData);
			this.stage.setChildIndex(this.OpenWinSceneMyGua,12)
			this.stage.setChildIndex(this.OpenWinSceneDiv,12)
			this.stage.setChildIndex(this.OpenWinScene,12)
			
			this.OpenWinScene.getReady();
			this.OpenWinSceneDiv.getReady(this.InitData);
			this.OpenWinSceneMyGua.getReady();
			this.containerScore.getChildById("numBmp").setText("X"+this.score);
			//console.log(this.stage)
        },

        // gameStart: function() {
        //     this.state = 'playing';
        //     this.gameReadyScene.visible = false;
        //     this.holdbacks.startMove();
        // },

        gameOver: function() {
            if (this.state !== 'over') {
                //设置当前状态为结束over
                this.state = 'over';
                //停止障碍的移动
                this.holdbacks.stopMove();
                //小鸟跳转到第一帧并暂停
                this.bird.goto(0, true);
                //隐藏屏幕中间显示的分数
                this.currentScore.visible = false;
                //显示结束场景
                this.gameOverScene.show(this.calcScore(), this.saveBestScore());
            }
        },

        calcScore: function() {
            var count = this.holdbacks.calcPassThrough(this.bird.x);
            return this.score = count;
        },

        saveBestScore: function() {
            var score = this.score,
                best = 0;
            if (Hilo.browser.supportStorage) {
                best = parseInt(localStorage.getItem('hilo-flappy-best-score')) || 0;
            }
            if (score > best) {
                best = score;
                localStorage.setItem('hilo-flappy-best-score', score);
            }
            return best;
        }
    };

})();